<template>
  <div class="command-list-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 右上角关闭按钮 -->
    <div class="page-close-btn">
      <el-button @click="goBack" class="close-button">
        <i class="fa fa-times"></i>
      </el-button>
    </div>

    <!-- 主要内容区域 -->
    <div class="command-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-terminal"></i>
              命令审计详情
            </h1>
            <p class="page-subtitle" v-if="sessionInfo">
              会话: {{ sessionInfo.user }}@{{ sessionInfo.host }} - {{ formatTime(sessionInfo.start_time) }}
            </p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ commands.length }}</div>
              <div class="stat-label">总命令数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ dangerousCommands }}</div>
              <div class="stat-label">危险命令</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ sessionDuration }}</div>
              <div class="stat-label">会话时长</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 命令列表 -->
      <div class="commands-section glass-effect">
        <div class="commands-header">
          <h3>
            <i class="fa fa-list"></i>
            命令执行记录
          </h3>
          <div class="filter-controls">
            <el-select v-model="riskFilter" placeholder="风险等级筛选" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="低风险" value="low"></el-option>
              <el-option label="中风险" value="medium"></el-option>
              <el-option label="高风险" value="high"></el-option>
              <el-option label="严重" value="critical"></el-option>
            </el-select>
          </div>
        </div>

        <el-table :data="filteredCommands" v-loading="loading" class="commands-table">
          <el-table-column prop="timestamp" label="执行时间" width="180">
            <template #default="scope">
              <span class="time-text">{{ formatTime(scope.row.timestamp) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="command" label="命令内容" min-width="300">
            <template #default="scope">
              <div class="command-cell">
                <code class="command-text" :class="{ 'dangerous': scope.row.is_dangerous }">
                  {{ scope.row.command }}
                </code>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="risk_level" label="风险等级" width="120">
            <template #default="scope">
              <el-tag :type="getRiskTagType(scope.row.risk_level)" size="small">
                {{ scope.row.risk_level_display || scope.row.risk_level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="执行时长" width="100">
            <template #default="scope">
              <span class="duration-text">{{ formatDuration(scope.row.duration) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="working_directory" label="工作目录" width="200">
            <template #default="scope">
              <span class="path-text">{{ scope.row.working_directory || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button @click="replayToCommand(scope.row)" class="glass-action-btn" size="small">
                <i class="fa fa-play"></i>
                <span>回放</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { formatTime } from '@/utils/format'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 获取会话ID
const sessionId = route.query.session_id as string

// 响应式数据
const sessionInfo = ref<any>(null)
const commands = ref<any[]>([])
const loading = ref(false)
const riskFilter = ref('')

// 计算属性
const filteredCommands = computed(() => {
  if (!riskFilter.value) return commands.value
  return commands.value.filter(cmd => cmd.risk_level === riskFilter.value)
})

const dangerousCommands = computed(() => {
  return commands.value.filter(cmd => cmd.is_dangerous).length
})

const sessionDuration = computed(() => {
  if (!sessionInfo.value?.duration) return '0秒'
  return formatDuration(sessionInfo.value.duration)
})

// 获取命令数据
const fetchCommands = async () => {
  if (!sessionId) {
    ElMessage.error('缺少会话ID参数')
    return
  }

  loading.value = true
  try {
    const response = await axios.get(`/api/audit/session-commands/?session_id=${sessionId}`)
    const data = response.data

    commands.value = data.commands || []
    sessionInfo.value = data.session_info || null

    console.log('命令数据加载完成:', commands.value.length)

  } catch (error) {
    console.error('获取命令数据失败:', error)
    ElMessage.error('获取命令数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化持续时间
const formatDuration = (seconds: number) => {
  if (!seconds || seconds < 1) return '<1秒'

  if (seconds < 60) {
    return `${Math.round(seconds)}秒`
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    const secs = Math.round(seconds % 60)
    return `${minutes}分${secs}秒`
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return `${hours}小时${minutes}分`
  }
}

// 获取风险等级标签类型
const getRiskTagType = (riskLevel: string) => {
  const typeMap: Record<string, string> = {
    'low': 'success',
    'medium': 'warning',
    'high': 'danger',
    'critical': 'danger'
  }
  return typeMap[riskLevel] || 'info'
}

// 回放到指定命令
const replayToCommand = (command: any) => {
  if (sessionId) {
    router.push(`/audit/replay/${sessionId}?command_time=${command.timestamp}`)
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期
onMounted(() => {
  fetchCommands()
})
</script>

<style lang="scss" scoped>
/* 主容器 */
.command-list-container {
  position: relative;
  height: 100vh;
  background: linear-gradient(135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  overflow: hidden; /* 防止无限滚动 */
}

/* 星空背景 */
.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

/* 右上角关闭按钮 */
.page-close-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 10000;
}

.close-button {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.15) !important;
  color: rgba(255, 255, 255, 0.8) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  border-radius: 50% !important;
  width: 40px !important;
  height: 40px !important;
  padding: 0 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  backdrop-filter: blur(20px) !important;
  box-shadow:
    inset 0 1px 0 rgba(255, 255, 255, 0.1),
    0 4px 15px rgba(0, 0, 0, 0.1) !important;
}

.close-button:hover {
  background: rgba(255, 255, 255, 0.08) !important;
  border-color: rgba(255, 182, 193, 0.4) !important;
  color: rgba(255, 182, 193, 0.9) !important;
  transform: scale(1.05) !important;
}

/* 主要内容区域 */
.command-content {
  position: relative;
  z-index: 10;
  height: 100vh;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  overflow-y: auto; /* 允许内容滚动，但限制在容器内 */
}

/* 玻璃效果基础样式 */
.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

/* 页面标题区域 */
.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section {
  flex: 1;
}

.page-title {
  color: #00eaff;
  font-size: 2.5em;
  margin: 0 0 10px 0;
  text-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
  display: flex;
  align-items: center;
  gap: 15px;

  i {
    font-size: 0.8em;
  }
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 1.1em;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;

  .stat-number {
    color: #00eaff;
    font-size: 2em;
    font-weight: bold;
    text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
  }

  .stat-label {
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.9em;
    margin-top: 5px;
  }
}

/* 命令列表区域 */
.commands-section {
  padding: 30px;
}

.commands-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    color: #00eaff;
    font-size: 1.5em;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
    text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
  }
}

.filter-controls {
  .el-select {
    width: 150px;
  }
}

.commands-table {
  background: transparent !important;

  :deep(.el-table__header) {
    background: rgba(164, 244, 186, 0.1);
  }

  :deep(.el-table__header th) {
    background: transparent;
    color: #00eaff;
    border-bottom: 1px solid rgba(164, 244, 186, 0.3);
    font-weight: bold;
  }

  :deep(.el-table__body tr) {
    background: transparent;
  }

  :deep(.el-table__body td) {
    background: transparent;
    color: rgba(255, 255, 255, 0.8);
    border-bottom: 1px solid rgba(164, 244, 186, 0.1);
  }

  :deep(.el-table__body tr:hover td) {
    background: rgba(164, 244, 186, 0.05) !important;
  }
}

.command-cell {
  padding: 5px 0;
}

.command-text {
  background: rgba(0, 0, 0, 0.3);
  padding: 4px 8px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #a4f4ba;
  border: 1px solid rgba(164, 244, 186, 0.2);

  &.dangerous {
    color: #ff6b6b;
    border-color: rgba(255, 107, 107, 0.3);
    background: rgba(255, 107, 107, 0.1);
  }
}

.time-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9em;
  font-family: monospace;
}

.duration-text {
  color: rgba(0, 234, 255, 0.8);
  font-size: 0.9em;
}

.path-text {
  color: rgba(164, 244, 186, 0.8);
  font-size: 0.9em;
  font-family: monospace;
}

.glass-action-btn {
  background: rgba(0, 234, 255, 0.1) !important;
  border: 1px solid rgba(0, 234, 255, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 6px !important;
  padding: 6px 10px !important;
  font-size: 12px !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  display: flex !important;
  align-items: center !important;
  gap: 4px !important;

  &:hover {
    background: rgba(0, 234, 255, 0.2) !important;
    border-color: rgba(0, 234, 255, 0.5) !important;
    color: rgba(0, 234, 255, 1) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 0 10px rgba(0, 234, 255, 0.3) !important;
  }
}
</style>
